﻿/* 
 * author: www.cnblogs.com/luminji
 * date  : 2011/11/18
 */
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Transactions;
using Luminji.Core.Data;
using Luminji.Infrastructure.DomainBase;
using Luminji.Infrastructure.RepositoryFramework;

namespace Luminji.Infrastructure.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        private class SqlUw
        {
            public string ConnectionString;
            public CommandType CommandType;
            public string CommandText;
            public SqlParameter[] CommandParameters;
        }
        
        private IList<SqlUw> uws;

        public UnitOfWork()
        {
            uws = new List<SqlUw>();
        }

        #region IUnitOfWork Members

        public void RegisterTextSql(string connectionString, CommandType commandType, string commandText, SqlParameter[] commandParameters)
        {
            uws.Add(
                new SqlUw()
                    {
                        ConnectionString =  connectionString,
                        CommandType =  commandType,
                        CommandText = commandText,
                        CommandParameters = commandParameters
                    });
        }

        public void Commit()
        {
            using (TransactionScope scope = new TransactionScope())
            {
                foreach (SqlUw item in uws)
                {
                    SqlHelper.ExecuteNonQuery(item.ConnectionString, item.CommandType, item.CommandText,item.CommandParameters);
                }

                
                scope.Complete();
            }
            uws.Clear();
        }

        #endregion
    }
}
